package com.linkoog.devtools.websocket.toolwindow.left;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.EditorSettings;
import com.intellij.openapi.project.Project;
import com.intellij.util.ui.AbstractTableCellEditor;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.EventObject;

public class EditorExTableCellEditor extends AbstractTableCellEditor implements Disposable {
    private final Project project;

    private final Editor editor;
    private final int editorOriginalCellHeight;

    public EditorExTableCellEditor(@NotNull Project project) {
        this.project = project;
        editor = EditorFactory.getInstance().createEditor(EditorFactory.getInstance().createDocument(""));

        final EditorSettings settings = editor.getSettings();
        settings.setAdditionalColumnsCount(0); //  additionalColumnsCount
        settings.setLineMarkerAreaShown(false); //isLineMarkerAreaShown
        settings.setAdditionalPageAtBottom(false);  //isAdditionalPageAtBottom
        settings.setRightMarginShown(false); //isRightMarginShown
        editorOriginalCellHeight = editor.getComponent().getFontMetrics(editor.getComponent().getFont()).getHeight();
    }

    @Override
    public boolean isCellEditable(EventObject e) {
        if (e instanceof MouseEvent){
            MouseEvent event = (MouseEvent) e;
            return event.getClickCount() == 2;
        }
        return false;
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        // Make the document change in the context of a write action.
        WriteCommandAction.runWriteCommandAction(project, () -> {
            final Document document = editor.getDocument();
            document.replaceString(0, document.getTextLength(), value.toString());
        });

        if (isSelected) {
            table.setRowHeight(row, 10 * editorOriginalCellHeight);
        }
        return editor.getComponent();
    }

    @Override
    public Object getCellEditorValue() {
        return editor.getDocument().getText();
    }

    @Override
    public void dispose() {
        EditorFactory.getInstance().releaseEditor(editor);
    }
}
